package com.lzw.demo.surfaceviewdemo.viewarch;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * SurfaceViewDemo
 * Created by lzw on 2018/12/24. 10:44:34
 * 邮箱：632393724@qq.com
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class CustomTextView extends android.support.v7.widget.AppCompatTextView {

    private Paint mpaint;

    private Rect rect ;

    {
        mpaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mpaint.setColor(Color.GREEN);

    }

    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 当指定宽高属性为Wrap_content时，如果不重写onMeasure 那么系统就不知道该使用默认多大的尺寸。
     * 所以重写onMeasure的目的，就是为了能够View
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
    }

    private int measureHeight(int heightMeasureSpec) {
        int result = 0;
        int specMode= MeasureSpec.getMode(heightMeasureSpec);
        int specSize= MeasureSpec.getSize(heightMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else if (specMode == MeasureSpec.AT_MOST){
            result = 200;
            result = Math.min(result,specSize);

        }
        return result;
    }

    private int measureWidth(int widthMeasureSpec) {
        int result = 0;
        int specMode= MeasureSpec.getMode(widthMeasureSpec);
        int specSize= MeasureSpec.getSize(widthMeasureSpec);
        if (specMode == MeasureSpec.EXACTLY){
            result = specSize;
        }else if (specMode == MeasureSpec.AT_MOST){
            result = 200;
            result = Math.min(result,specSize);

        }
        return result;
    }

    /**
     * 对现有控件进行拓展，这是一个非常重要的自定义view方法，它可以在原生控件的基础上进行拓展，增加
     * 新的功能、UI等。一般来说，我们可以在onDraw方法中对原生控件行为进行拓展
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        rect = new Rect(0,0,getMeasuredWidth(),getMeasuredHeight());
        canvas.drawRect(rect,mpaint);
        //在回调父类方法前，实现自己的逻辑，对于TextView来说即是在绘制文本内容前
        super.onDraw(canvas);
        //在回调父类方法后，实现自己的逻辑，对于TextView来说即是在绘制文本内容后
    }
}
